/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class MyJdbc {

    private final static String DRIVER = "com.mysql.jdbc.Driver";
    private final static String URL = "jdbc:mysql://localhost:3306/login";
    private final static String Name = "scott";
    private final static String Password = "tiger";
    private Connection con = null;
    private PreparedStatement pstate = null;
    private ResultSet res = null;

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MyJdbc.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public MyJdbc() {
    }

    public Connection getConnection() {
        try {
            con = DriverManager.getConnection(URL, Name, Password);
        } catch (SQLException ex) {
            Logger.getLogger(MyJdbc.class.getName()).log(Level.SEVERE, null, ex);
        }
        return con;
    }

    public ResultSet query(String sqlString) throws Exception {
        pstate = createStatement(sqlString);
        return pstate.executeQuery();
    }

    public ResultSet query(String sqlString, Object... params) throws Exception {
        pstate = createStatement(sqlString, params);
        return pstate.executeQuery();
    }

    public int update(String sqlString, Object... params) throws Exception {
        pstate = createStatement(sqlString, params);
        return pstate.executeUpdate();
    }

    private PreparedStatement createStatement(String sqlString, Object... params) throws SQLException {
        pstate = getConnection().prepareStatement(sqlString);
        for (int i = 0; i < params.length; i++) {
            Object param = params[i];
            pstate.setObject(i + 1, param);
        }
        return pstate;
    }
    public  void close() throws SQLException {
        if (res != null) {
            res.close();
        }
        if (pstate != null) {
            pstate.close();
        }
        if (con != null) {
            con.close();
        }
    }
}
